package org.tobaccomain.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tobaccomain.service.UdpService;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.concurrent.ExecutorService;

@Slf4j
@Component
public class UdpReceiver {

    @Autowired
    private ExecutorService executorService;

    @Autowired
    private UdpService udpService;

    public void start() {
        executorService.submit(this::run);
    }

    public void run() {
        DatagramSocket socket = null;
        try {
            log.info("开始接收网络发送过来的rfid的信息...");
            socket = new DatagramSocket(8080); // 监听的端口号
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            while (true) {
                socket.receive(packet);
                String data = new String(packet.getData(), 0, packet.getLength());
//                log.info("接受到的数据:{}",data);
                udpService.receiveData(data, packet.getAddress(), packet.getPort());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }
}
